package com.shujia.source

import org.apache.flink.streaming.api.scala._
import org.apache.flink.api.common.eventtime.WatermarkStrategy
import org.apache.flink.api.common.serialization.SimpleStringSchema
import org.apache.flink.connector.kafka.source.KafkaSource
import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer

object Demo4KafkaSource {
  def main(args: Array[String]): Unit = {
    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment


    /**
      * 4、kafka source   -- 无界流
      *
      */
    val source: KafkaSource[String] = KafkaSource
      .builder[String]
      .setBootstrapServers("master:9092") // kafka 集群的列表
      .setTopics("test_topic2") //消费的topic
      .setGroupId("my-group") //消费者组
      .setStartingOffsets(OffsetsInitializer.earliest()) //指定读取数据的位置
      .setValueOnlyDeserializer(new SimpleStringSchema()) //指定反序列化数据的类
      .build

    val kafkaDS: DataStream[String] = env.fromSource(source, WatermarkStrategy.noWatermarks(), "Kafka Source")


    kafkaDS
      .flatMap(_.split(","))
      .map((_, 1))
      .keyBy(_._1)
      .sum(1)
      .print()

    env.execute()

  }

}
